package com.siruier.boss.ui.activity.mall

import android.graphics.Paint
import android.view.View
import androidx.core.view.isVisible
import com.alibaba.fastjson.JSON
import com.bumptech.glide.Glide
import com.kingja.loadsir.core.LoadService
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.util.SmartGlideImageLoader
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.api.core.toData
import com.siruier.boss.api.mallApi
import com.siruier.boss.bean.MallGoodsBean
import com.siruier.boss.bean.MallGoodsProductBean
import com.siruier.boss.bean.MallGoodsSpecInfoBean
import com.siruier.boss.bean.UserLevelEnum
import com.siruier.boss.common.formatPriceRmb
import com.siruier.boss.databinding.ActivityMallGoodsBinding
import com.siruier.boss.ui.activity.main.MainActivity
import com.siruier.boss.ui.api.ApiObserver
import com.siruier.boss.ui.base.BaseActivity
import com.siruier.boss.ui.cache.UserCache
import com.siruier.boss.ui.dialog.ProductSpecDialog
import com.siruier.boss.ui.ext.showLoadingCallback
import com.siruier.boss.ui.ext.startActivityExt
import com.siruier.boss.ui.helper.InjectBundle
import com.siruier.boss.ui.helper.ShareHelper
import com.siruier.boss.ui.helper.loadsir.LoadSirHelper
import com.umeng.socialize.ShareAction
import com.umeng.socialize.bean.SHARE_MEDIA
import com.yanzhenjie.sofia.Utils
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator


class MallGoodsActivity : BaseActivity<ActivityMallGoodsBinding>() {
    private val mGoodsId: Int by InjectBundle()
    private val mLoadService: LoadService<*> by lazy { LoadSirHelper.register(vb.rootView) { onReload() } }
    private var mMallGoodsBean: MallGoodsBean? = null
    private var mProductSpecDialog: ProductSpecDialog? = null
    override fun initView() {
        Utils.invasionStatusBar(this)
        bindViewClick(vb.ivToUp, vb.ivBack, vb.tvSpec, vb.buttonBuyNow, vb.ivShare, vb.ivGoodsUp)
    }

    override fun initData() {
        mLoadService.showLoadingCallback()
        onReload()
    }

    override fun onClick(v: View?) {
        when (v) {
            vb.ivShare -> {
                ShareAction(mThis)
                    .setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                    .addButton("保存图片", "save_image", "icon_share_save_image", "icon_share_save_image")
                    .setShareboardclickCallback { snsPlatform, shareMedia ->
                        if (SHARE_MEDIA.WEIXIN == shareMedia) {
                            mMallGoodsBean?.apply {
                                val galleryArr = JSON.parseArray(gallery, String::class.java)
                                ShareHelper.goodsShareWx(
                                    this@MallGoodsActivity, vb.viewGoodsShareWx, galleryArr[0], name,
                                    (bossPrice ?: agentPrice ?: retailPrice).formatPriceRmb(),
                                    marketPrice.formatPriceRmb(), mGoodsId
                                )
                            }
                        } else if (SHARE_MEDIA.WEIXIN_CIRCLE == shareMedia || "save_image" == snsPlatform.mKeyword) {
                            mMallGoodsBean?.apply {
                                val galleryArr = JSON.parseArray(gallery, String::class.java)
                                ShareHelper.goodsShareWxCircle(
                                    mThis, mThis, vb.viewGoodsShareWeixinCircle, "save_image" == snsPlatform.mKeyword,
                                    galleryArr[0], name, (bossPrice ?: agentPrice ?: retailPrice).formatPriceRmb(), mGoodsId
                                )
                            }
                        }
                    }
                    .open()
            }
            vb.ivBack -> finish()
            vb.ivToUp -> vb.scrollView.smoothScrollTo(0, 0)
            vb.buttonBuyNow, vb.tvSpec -> mProductSpecDialog?.show()
            vb.ivGoodsUp -> startActivityExt<MainActivity> {
                putExtra("changePage", "agent_join")
            }
        }
    }

    private fun buyNow(goodsSpecBean: MallGoodsProductBean, number: Int) {
        startActivityExt<ConfirmOrderActivity> {
            putExtra("type", mMallGoodsBean?.type)
            putExtra("mGoodsId", mGoodsId)
            putExtra("mGoodsNum", number)
            putExtra("mGoods", mMallGoodsBean)
            putExtra("mGoodsSpecnId", goodsSpecBean.specificationsId)
        }
    }

    private fun onReload() {
        launchUI({
            val mMallGoodsBean = mallApi.goodsDetail(mGoodsId).toData()
            handGoodsDetail(mMallGoodsBean)
            handMallGoodsSpec(mMallGoodsBean?.name, mMallGoodsBean?.type, mallApi.goodsSpecn(mGoodsId).toData())
        }, ApiObserver(loadService = mLoadService))
    }

    private fun handGoodsDetail(mallGoodsBean: MallGoodsBean?) {
        mMallGoodsBean = mallGoodsBean
        mMallGoodsBean?.apply {
            val galleryArr = JSON.parseArray(gallery, String::class.java) ?: mutableListOf()
            galleryArr.forEachIndexed { index, url ->
                if (index > 0) {
                    Glide.with(mThis)
                        .load(url)
                        .submit()
                }
            }
            vb.banner.setAdapter(object : BannerImageAdapter<String>(galleryArr) {
                override fun onBindView(holder: BannerImageHolder, data: String, position: Int, size: Int) {
                    Glide.with(holder.itemView)
                        .load(data)
                        .into(holder.imageView)
                    holder.imageView.setOnClickListener {
                        XPopup.Builder(mThis)
                            .asImageViewer(holder.imageView, position, galleryArr.toList(), null, SmartGlideImageLoader())
                            .show()
                    }
                }
            })
            vb.banner.addBannerLifecycleObserver(mThis)
            vb.banner.indicator = CircleIndicator(mThis)

            vb.tvMemberPrice.text = priceDesc

            vb.llPrice.isVisible = agentPrice != null
            vb.tvCurrentPriceMany.isVisible = agentPrice != null

            vb.tvVipPrice.text = priceDesc
            vb.llDlPrice.isVisible = agentPrice != null
            vb.llLbPrice.isVisible = bossPrice != null
            if (agentPrice != null) {
                vb.tvDlPrice.text = agentPrice.formatPriceRmb()
                if (UserCache.getUserInfoBean().userLevel == UserLevelEnum.AGENT.level) {
                    vb.tvCurrentPriceMany.text = "当前价格为${UserLevelEnum.AGENT.levelName}价"
                    vb.tvMemberPrice.text = agentPrice.formatPriceRmb()
                }
            }
            if (bossPrice != null) {
                vb.tvLbPrice.text = bossPrice.formatPriceRmb()
                if (UserCache.getUserInfoBean().userLevel == UserLevelEnum.BOSS.level) {
                    vb.tvCurrentPriceMany.text = "当前价格为${UserLevelEnum.BOSS.levelName}价"
                    vb.tvMemberPrice.text = bossPrice.formatPriceRmb()
                }
            }
            vb.tvMarketPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
            vb.tvMarketPrice.text = marketPrice.formatPriceRmb()
            vb.tvFree.text = freightPrice.formatPriceRmb()
            vb.tvName.text = name
            vb.wbDetail.loadData("""<style>img{max-width:100%;height:auto}</style>$detail""", "text/html; charset=UTF-8", null)
        }
    }

    private fun handMallGoodsSpec(name: String?, type: Int?, mallGoodsSpecInfoBean: MallGoodsSpecInfoBean?) {
        if (mallGoodsSpecInfoBean != null) {
            mProductSpecDialog = ProductSpecDialog(this, name, type, mallGoodsSpecInfoBean, ::buyNow)
        }
    }

}